
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2024-03-14
 * Time: 20:28
 */
public class JDBCDemo {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //1.创建数据源,数据源描述了你需要操作的数据库在哪里
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java111?characterEncoding=utf8&useSSL=false");
            //默认自带一个管理员账户root(权限最大的账户)
        ((MysqlDataSource)dataSource).setUser("root");
            //登录密码
        ((MysqlDataSource)dataSource).setPassword("1234");

        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();

        //3.能够构造一个操作数据库的sql语句
        System.out.println("请输入学号: ");
        int id = scanner.nextInt();
        System.out.println("请输入姓名: ");
        String name = scanner.next();

       //String sql = "insert into values("+id +", '"+name+"')";  可读性差,不建议使用

        //3.构造sql语句(利用占位符)
        String str = "insert into student values(?,?)";  //增加

        //需要把 String str 转成 语句对象
        PreparedStatement preparedStatement = connection.prepareStatement(str);
        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);

        //第一种方法
//        String str = "insert into student values(1,'小黄'),(2,'小红')";
//        PreparedStatement preparedStatement = connection.prepareStatement(str);

        //4.执行sql语句,
            //返回值是一个int型的,表示操作影响(成功执行)了几行数据
        int n = preparedStatement.executeUpdate();
        System.out.println("n = "+n);

        //5.释放前面创建的各种资源
        preparedStatement.close();
        connection.close();

    }
}
